package com.uziot.bucket.rest.template.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.lang.Nullable;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;

/**
 * @author shidt
 * @version V1.0
 * @className AbstractPostExchangeDataService
 * @date 2020-08-19 19:54:25
 * @description
 */
@Slf4j
public abstract class AbstractPostExchangeDataService implements PostExchangeDataService {

    @Autowired
    public RestTemplate restTemplate;

    @Override
    public String postFormData(String url, @Nullable MultiValueMap<String, Object> multiValueMap) {

        // 组装消息头
        ArrayList<MediaType> acceptMediaTypes = new ArrayList<>();
        acceptMediaTypes.add(MediaType.APPLICATION_JSON);
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(acceptMediaTypes);
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 执行请求
        HttpEntity<Object> httpEntity = new HttpEntity<>(multiValueMap, headers);
        ResponseEntity<String> serviceResponse = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return serviceResponse.getBody();
    }


    @Override
    public Object multiPostForObject(String firstUri, String secondUri, Object firstReq, Object secondReq) {
        // 前置处理
        Object preFirstReq = this.beforeFirstRequest(firstReq);
        // 请求A系统
        Object firstResp = restTemplate.postForObject(firstUri, preFirstReq, Object.class);
        // 是否执行第二请求
        boolean support = this.support(preFirstReq, firstResp, secondReq);
        if (!support) {
            return firstResp;
        }
        // 交换信息
        secondReq = this.exchange(preFirstReq, firstResp, secondReq);
        // 请求B系统
        Object secondResp = restTemplate.postForObject(secondUri, secondReq, Object.class);
        // 后置消息处理返回
        return this.afterPostResponse(firstResp, secondResp);
    }


    public Object beforeFirstRequest(Object firstReq) {
        return firstReq;
    }

    public Object afterPostResponse(Object firstResp, Object secondResp) {
        return firstResp;
    }

    public RestTemplate getRestTemplate() {
        return restTemplate;
    }

    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
}
